package whu.iss.web.sys;

import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import whu.iss.pojo.EssayCustom;
import whu.iss.pojo.UserCustom;
import whu.iss.services.impl.sys.PublishServices;
import whu.iss.system.tools.Tools;

@WebServlet(value="/publish")
public class PublishServlet extends HttpServlet
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		request.setCharacterEncoding("UTF-8");
		String toPath="publish.jsp";
		try
		{	
			//获取页面数据	
			String type=request.getParameter("essaytype");
			String title=request.getParameter("essaytitle");
			String preview=null;
			String body=request.getParameter("essaybody");
			int number=0;
			int uid=1;
            Date date=new Date();
            String privacy=request.getParameter("essayprivacy");
			
			//实例化Services
			PublishServices services=new PublishServices();
			EssayCustom essaycustom=new EssayCustom();
			
            
			if(!body.equals("") && body!=null) 
			{
				//计算正文字数
				number=Tools.getCount(body);
				//截取文章预览
				if(number>80) 
				{
					preview=body.substring(0, 80);
				}
				else 
				{
					preview=body;
				}
				//设置数据，存入数据库
				essaycustom.setBody(body);
				if(title!=null) 
				{
					essaycustom.setTitle(title);
				}
				essaycustom.setDate(date);
				essaycustom.setPrivacy(privacy);
				essaycustom.setNumber(number);
				essaycustom.setPreview(preview);
				essaycustom.setType(type);
				essaycustom.setUserid(uid);
				services.insertEssay(essaycustom);
				toPath="main.jsp";
			}
			else 
			{
				toPath="publish.jsp";
			}
			

		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		request.getRequestDispatcher("/"+toPath).forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		this.doGet(request, response);
	}

}
